// 任务管理应用
document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const taskForm = document.getElementById('task-form');
    const taskInput = document.getElementById('task-input');
    const tasksContainer = document.getElementById('tasks-container');
    const filterButtons = document.querySelectorAll('.filter-btn');
    const totalCountElement = document.getElementById('total-count');
    const completedCountElement = document.getElementById('completed-count');
    
    // 任务数组
    let tasks = [];
    
    // 当前过滤器
    let currentFilter = 'all';
    
    // 从本地存储加载任务
    function loadTasks() {
        const storedTasks = localStorage.getItem('tasks');
        if (storedTasks) {
            tasks = JSON.parse(storedTasks);
        }
        renderTasks();
        updateStats();
    }
    
    // 保存任务到本地存储
    function saveTasks() {
        localStorage.setItem('tasks', JSON.stringify(tasks));
    }
    
    // 添加新任务
    function addTask(text) {
        const newTask = {
            id: Date.now(),
            text: text,
            completed: false,
            createdAt: new Date().toISOString()
        };
        
        tasks.push(newTask);
        saveTasks();
        renderTasks();
        updateStats();
    }
    
    // 删除任务
    function deleteTask(id) {
        tasks = tasks.filter(task => task.id !== id);
        saveTasks();
        renderTasks();
        updateStats();
    }
    
    // 切换任务完成状态
    function toggleTaskCompletion(id) {
        tasks = tasks.map(task => {
            if (task.id === id) {
                return { ...task, completed: !task.completed };
            }
            return task;
        });
        saveTasks();
        renderTasks();
        updateStats();
    }
    
    // 编辑任务
    function editTask(id, newText) {
        tasks = tasks.map(task => {
            if (task.id === id) {
                return { ...task, text: newText };
            }
            return task;
        });
        saveTasks();
        renderTasks();
    }
    
    // 渲染任务列表
    function renderTasks() {
        tasksContainer.innerHTML = '';
        
        // 根据当前过滤器筛选任务
        let filteredTasks = tasks;
        if (currentFilter === 'pending') {
            filteredTasks = tasks.filter(task => !task.completed);
        } else if (currentFilter === 'completed') {
            filteredTasks = tasks.filter(task => task.completed);
        }
        
        // 如果没有任务，显示提示信息
        if (filteredTasks.length === 0) {
            const emptyMessage = document.createElement('li');
            emptyMessage.className = 'empty-message';
            emptyMessage.textContent = currentFilter === 'all' ? '暂无任务，添加一个吧！' : 
                                      currentFilter === 'pending' ? '没有待完成的任务' : 
                                      '没有已完成的任务';
            tasksContainer.appendChild(emptyMessage);
            return;
        }
        
        // 渲染每个任务
        filteredTasks.forEach(task => {
            const taskItem = document.createElement('li');
            taskItem.className = `task-item ${task.completed ? 'completed' : ''}`;
            taskItem.dataset.id = task.id;
            
            taskItem.innerHTML = `
                <input type="checkbox" class="task-checkbox" ${task.completed ? 'checked' : ''}>
                <span class="task-text">${task.text}</span>
                <div class="task-actions">
                    <button class="edit-btn">编辑</button>
                    <button class="delete-btn">删除</button>
                </div>
            `;
            
            tasksContainer.appendChild(taskItem);
            
            // 添加事件监听器
            const checkbox = taskItem.querySelector('.task-checkbox');
            const editButton = taskItem.querySelector('.edit-btn');
            const deleteButton = taskItem.querySelector('.delete-btn');
            
            checkbox.addEventListener('change', () => {
                toggleTaskCompletion(task.id);
            });
            
            editButton.addEventListener('click', () => {
                const newText = prompt('编辑任务:', task.text);
                if (newText && newText.trim() !== '') {
                    editTask(task.id, newText.trim());
                }
            });
            
            deleteButton.addEventListener('click', () => {
                if (confirm('确定要删除这个任务吗？')) {
                    deleteTask(task.id);
                }
            });
        });
    }
    
    // 更新任务统计
    function updateStats() {
        const totalCount = tasks.length;
        const completedCount = tasks.filter(task => task.completed).length;
        
        totalCountElement.textContent = totalCount;
        completedCountElement.textContent = completedCount;
    }
    
    // 设置过滤器
    function setFilter(filter) {
        currentFilter = filter;
        
        // 更新按钮状态
        filterButtons.forEach(button => {
            if (button.dataset.filter === filter) {
                button.classList.add('active');
            } else {
                button.classList.remove('active');
            }
        });
        
        renderTasks();
    }
    
    // 事件监听器
    taskForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const text = taskInput.value.trim();
        if (text) {
            addTask(text);
            taskInput.value = '';
        }
    });
    
    filterButtons.forEach(button => {
        button.addEventListener('click', function() {
            setFilter(this.dataset.filter);
        });
    });
    
    // 初始化应用
    loadTasks();
});